﻿//  Copyright 2022 Google LLC. All Rights Reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

using System;
using System.IO;
using System.Text;

namespace NtCoreLib.Win32.Security.Authentication.Kerberos.Builder;

/// <summary>
/// Class to represent a PAC_CLIENT_INFO builder.
/// </summary>
public sealed class KerberosAuthorizationDataPACClientInfoBuilder : KerberosAuthorizationDataPACEntryBuilder
{
    /// <summary>
    /// Client ID.
    /// </summary>
    public long ClientId { get; set; }
    /// <summary>
    /// Name of client.
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Constructor.
    /// </summary>
    public KerberosAuthorizationDataPACClientInfoBuilder() 
        : base(KerberosAuthorizationDataPACEntryType.ClientInfo)
    {
    }

    internal KerberosAuthorizationDataPACClientInfoBuilder(KerberosAuthorizationDataPACClientInfo info) 
        : this()
    {
        ClientId = info.ClientId;
        Name = info.Name;
    }

    /// <summary>
    /// Create the real PAC entry.
    /// </summary>
    /// <returns>The created PAC entry.</returns>
    public override KerberosAuthorizationDataPACEntry Create()
    {
        MemoryStream stm = new();
        BinaryWriter writer = new(stm);

        if (Name is null)
            throw new ArgumentNullException(nameof(Name));

        byte[] data = Encoding.Unicode.GetBytes(Name);
        ushort len = (ushort)data.Length;

        writer.Write(ClientId);
        writer.Write(len);
        writer.Write(data);

        if (!KerberosAuthorizationDataPACClientInfo.Parse(stm.ToArray(), 
            out KerberosAuthorizationDataPACEntry entry))
        {
            throw new InvalidDataException("Invalid PAC entry.");
        }
        return entry;
    }
}
